package com.example.order.service;

import com.example.order.client.AccountClient;
import com.example.order.client.StorageClient;
import com.example.order.dao.OrderMapper;
import com.example.order.entity.Order;
import feign.FeignException;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@RequiredArgsConstructor
public class OrderService {

    private final AccountClient accountClient;
    private final StorageClient storageClient;
    private final OrderMapper orderMapper;

//    @Transactional
    @GlobalTransactional
    public Long create(Order order) {
        // 创建订单
        orderMapper.insert(order);
        try {
            accountClient.deduct(order.getUserId(), order.getMoney());
            log.info("扣除用户余额成功.");

            storageClient.deduct(order.getCommodityCode(), order.getCount());
            log.info("扣扣减库存成功.");

        } catch (FeignException e) {
            log.error("下单失败，原因:{}", e.contentUTF8(), e);
            throw new RuntimeException(e.contentUTF8(), e);
        }
        return order.getId();
    }

}
